package com.liwei.easyweibo.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.liwei.easyweibo.activity.WriteWeiboActivity;
import com.sina.net.AccessToken;
import com.tencent.weibo.oauthv2.OAuthV2;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

/**
 * 工具类
 * */
public class Util {
	private static boolean mIsLog = true;  //打印日志的开关
	private static final String PREFERENCES_NAME = "com_weibo_sdk_android";
	
	public static void writeToPreference(Context context,String name,String content){
		SharedPreferences preference = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
		Editor editor = preference.edit();
		editor.putString(name, content);
		editor.commit();
	}
	
	public static void writeToPreference(Context context,String name,boolean isTrue){
		SharedPreferences preference = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
		Editor editor = preference.edit();
		editor.putBoolean(name, isTrue);
		editor.commit();
	}
	
	public static String readSFromPreference(Context context,String name){
		SharedPreferences preference = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
		return preference.getString(name, "");
	}
	
	public static boolean readBFromPreference(Context context,String name){
		SharedPreferences preference = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
		return preference.getBoolean(name,false);
	}
	
	public static void showToast(Context context,String content){
		Toast.makeText(context, content, Toast.LENGTH_LONG).show();
	}
	
	public static void showToast(Context context,int content){
		Toast.makeText(context, content, Toast.LENGTH_LONG).show();
	}
	
	public static void showToast(Context context,int content,int Duration){
		Toast.makeText(context, content, Duration).show();
	}
	
	public static void d(String tag,String content){
		if(mIsLog){
			Log.d(tag, content);
		}
	}
	
	/**
     * Returns true if the string is null or 0-length.
     * @param str the string to be examined
     * @return true if str is null or zero length
     */
	public static boolean isEmpty(CharSequence str){
		if(str == null || str.length() == 0)
			return true;
		else
			return false;
	}
	
	/**
	 * 保存accesstoken到SharedPreferences
	 * @param context Activity 上下文环境
	 * @param token Oauth2AccessToken
	 */
	public static void keepSinaAccessToken(Context context, AccessToken token) {
		SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
		Editor editor = pref.edit();
		editor.putString(Constant.SHAREDPRE_SINA_TOKEN, token.getToken());
		editor.putString(Constant.SHAREDPRE_SINA_SECRET, token.getSecret());
		editor.commit();
	}
	/**
	 * 清空sharepreference
	 * @param context
	 */
	public static void clear(Context context){
	    SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
	    Editor editor = pref.edit();
	    editor.clear();
	    editor.commit();
	}
	
	/**
	 * 保存accesstoken到SharedPreferences
	 * @param context Activity 上下文环境
	 * @param token Oauth2AccessToken
	 */
	public static void keepTencentAccessToken(Context context, OAuthV2 oauth) {
		SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
		Editor editor = pref.edit();
		String str = null;
		try{
			str = writeObject(oauth);
		}catch(Exception e){
			
		}
		editor.putString(Constant.SHAREDPRE_TENCENT_OAUTH, str);
		editor.commit();
	}
	
	/**
	 * 读取腾讯微博的认证信息
	 * */
	public static OAuthV2 readTencentFromPreference(Context context){
		SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
		String object = pref.getString(Constant.SHAREDPRE_TENCENT_OAUTH, null);
		OAuthV2 oauth = null;
		try {
			 oauth = (OAuthV2) readObject(object);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return oauth;
	}
	
	/**
	 * 序列化对象为String字符串
	 * 
	 * @param o
	 *            Object
	 * @return String
	 * @throws Exception
	 */
	public static String writeObject(Object o) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(o);
		oos.flush();
		oos.close();
		bos.close();
		return Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT);
	}
	/**
	 * 序列化字符串为对象
	 * @throws IOException 
	 * @throws StreamCorruptedException 
	 * */
	public static Object readObject(String object) throws Exception{
		byte[] buf = Base64.decode(object, Base64.DEFAULT);
		ByteArrayInputStream bis = new ByteArrayInputStream(buf);
		ObjectInputStream ois = new ObjectInputStream(bis);
		Object o = ois.readObject();
		bis.close();
		ois.close();
		return o;
	}
	
	public static boolean isBindToSina(Context context){
		SharedPreferences sp = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
		String accessToken 		= sp.getString(Constant.SHAREDPRE_SINA_SECRET, "");
		String accessSecret 	= sp.getString(Constant.SHAREDPRE_SINA_SECRET, "");
		return !"".equals(accessToken) && !"".equals(accessSecret);
	}
	
	/** Create a file Uri for saving an image or video */
	public static Uri getOutputMediaFileUri(int type){
	      return Uri.fromFile(getOutputMediaFile(type));
	}

	/** Create a File for saving an image or video */
	private static File getOutputMediaFile(int type){
	    // To be safe, you should check that the SDCard is mounted
	    // using Environment.getExternalStorageState() before doing this.

	    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	              Environment.DIRECTORY_PICTURES), "EasyWeiboApp");
	    // This location works best if you want the created images to be shared
	    // between applications and persist after your app has been uninstalled.

	    // Create the storage directory if it does not exist
	    if (! mediaStorageDir.exists()){
	        if (! mediaStorageDir.mkdirs()){
	            Log.d("MyCameraApp", "failed to create directory");
	            return null;
	        }
	    }

	    // Create a media file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    File mediaFile;
	    if (type == Constant.MEDIA_TYPE_IMAGE){
	    	Util.d("mycamera", "camera = "+mediaStorageDir.getPath());
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "IMG_"+ timeStamp + ".jpg");
	    } else if(type ==Constant. MEDIA_TYPE_VIDEO) {
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "VID_"+ timeStamp + ".mp4");
	    } else {
	        return null;
	    }

	    return mediaFile;
	}
	
	public static boolean isBindToWeibo(Context context){
		boolean isBindToSina = Util.isBindToSina(context);
		OAuthV2 oauth = Util.readTencentFromPreference(context);
		return isBindToSina || (oauth != null);
	}
	
	public static String  clearSlash(String str){
		String spiltStr  =  "\\";
		String newStr = str.replace(spiltStr, "");
		return newStr;
	}
}
